import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../utils/overscroll_config/overscroll_config.dart';

class NestedScrollTestPage extends StatefulWidget {
  const NestedScrollTestPage({Key? key}) : super(key: key);

  @override
  State<NestedScrollTestPage> createState() => _NestedScrollTestPageState();
}

class _NestedScrollTestPageState extends State<NestedScrollTestPage> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
  }

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 2000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  // todo: 一个问题未解决，offset为0时，在顶部，滑动header列表，下面的嵌套列表会被滑动。希望都不滑动
  @override
  Widget build(BuildContext context) {
    return Material(
      child: NestedScrollView(
        // 无效
        physics: const BouncingScrollPhysics(),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          // 返回一个 Sliver 数组给外部可滚动组件。
          return <Widget>[
            // 也可以在这写appbar
            SliverAppBar(
              title: const Text('嵌套ListView'),
              pinned: true, // 固定在顶部
              forceElevated: innerBoxIsScrolled,
            ),
            ..._buildSliverList(15), //构建一个 sliverList
          ];
        },
        body: ScrollConfiguration(
          behavior: NoOverScrollBehavior(),
          child: SmartRefresher(
            controller: _refreshController,
            onRefresh: _onRefresh,
            header: const WaterDropHeader(),
            enablePullDown: true,
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              physics: const ClampingScrollPhysics(), //重要
              itemCount: 30,
              itemBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 50,
                  child: Center(child: Text('Item $index')),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildSliverList(int count) {
    List<Widget> list = [];
    for (int i = 0; i < count; i++) {
      list.add(SliverToBoxAdapter(
        child: Container(
          alignment: Alignment.center,
          height: 30,
          child: Text(i.toString()),
        ),
      ));
    }
    return list;
  }
}
